<template>
  <div class="shop_code">
    <div class="warn-box">
      <svg-icon
        style="margin-right: 17px"
        icon-class="warn"
        :size="20"
      />
      <p class="color-666"><span
          class="font-16"
          style="line-height:35px"
        >店铺二维码说明</span><br />1. 商家生成下载店铺二维码进行推广宣传，通过扫描二维码下单的手续费率为1.5-8%区间。</p>
    </div>
    <div class="flex align-center">
      <el-image
        style="width:250px; height:250px"
        :src="codeUrl?codeUrl:''"
      >
        <div
          slot="error"
          class="image-slot"
        >
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
      <el-button
        style="margin-left:45px"
        type="primary"
        @click="download"
      >下载店铺二维码</el-button>
    </div>
  </div>
</template>

<script>
import { shopQrcode } from "@/api/shop";
export default {
  data() {
    return {
      codeUrl: ''
    }
  },
  methods: {
    download() {
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'Anonymous')
      image.onload = function () {
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        let context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
        let a = document.createElement('a') // 生成一个a元素
        let event = new MouseEvent('click') // 创建一个单击事件
        a.download = '店铺二维码'
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      };
      image.crossOrigin = '' // 切记一定要将这个放在src赋值前,要不然会在safari上报安全错误
      image.src = this.codeUrl;
    },
    getData() {
      shopQrcode().then(res => {
        this.codeUrl = res.data.qr_code_url;
      })
    }
  },
  mounted() {
    this.getData();
  }
}
</script>
<style lang="scss" scoped>
.shop_code {
  padding: 20px 30px;
  background-color: #f5f5f5;
}
</style>